package com.shuigu.common.utils.translation;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class YouDaoUtil {

    // 您的应用ID
    private static final String APP_KEY = "22f664aac198c331";
    // 您的应用密钥
    private static final String APP_SECRET = "k0tvtQQS8hU6gTgmUiXRNBV9QbiYY9b4";

    /**
     *
     * @param q 待翻译文本
     * @param from 源语言语种
     * @param to 目标语言语种
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String transform(String q, String from, String to){
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(q, from, to);
        // 添加鉴权相关参数
        try {
            AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json");
        // 打印返回结果
        if (result != null) {
            return new String(result, StandardCharsets.UTF_8);
        }

        return "";
    }

    private static Map<String, String[]> createRequestParams(String q, String from, String to) {
        /*
         * note: 将下列变量替换为需要请求的参数
         * 取值参考文档: https://ai.youdao.com/DOCSIRMA/html/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E7%BF%BB%E8%AF%91/API%E6%96%87%E6%A1%A3/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1-API%E6%96%87%E6%A1%A3.html
         */
        String vocabId = "您的用户词表ID";

        return new HashMap<String, String[]>() {{
            put("q", new String[]{q});
            put("from", new String[]{from});
            put("to", new String[]{to});
            put("vocabId", new String[]{vocabId});
        }};
    }
}
